import {defineStore} from 'pinia'
import {ref, computed} from "vue";
import {getUserInfoApi, logoutApi} from "@/api/auth/index.ts"

export const useUserAuthStore = defineStore('userAuthStore', () => {
        // 定义 store 中的状态
        const token = ref();
        // 姓名
        const name = ref();
        // 用户id
        const userId = ref();
        // 权限值
        const permissions = ref([]);

        // 设置token
        const setToken = (tokenData: string) => {
            token.value = tokenData;
        };

        // 清理数据
        const clearAuthInfo = () => {
            token.value = '';
            name.value = '';
            userId.value = '';
            permissions.value = [];
        }

        // 退出登陆
        const logout = async () => {
            await logoutApi();
            clearAuthInfo();
        };

        // 获取用户信息
        const getUserInfo = () => {
            return new Promise((resolve, reject) => {
                getUserInfoApi().then((res: any) => {
                    name.value = res.data.name;
                    userId.value = res.data.userId;
                    permissions.value = res.data.permissions;
                    resolve(res);
                }).catch((error) => {
                    reject(error);
                });
            });
        };

        return {userId, name, permissions, token, setToken, getUserInfo, logout,clearAuthInfo};
    },
    {
        persist: {
            pick: ['token', 'userId'] // 仅缓存 token 和 userId
        },
    });
